#include <ulib.h>
#include <file.h>
#include <stat.h>
#include <unistd.h>
#include <dir.h>

#define BUFSIZE         4096
#define printf(...)		fprintf(1,__VA_ARGS__)

int
mv(int srcfd, int destfd, char* oldname) {
    static char buffer[BUFSIZE];
    int ret1, ret2;
    while ((ret1 = read(srcfd, buffer, sizeof(buffer))) > 0) {
        if ((ret2 = write(destfd, buffer, ret1)) != ret1) {
            return ret2;
        }
    }
    close(srcfd);
    if (unlink(oldname) < 0) {
        printf("delete %s failed\n", oldname);
    }
    return ret1;
}

void
usage(void) {
    printf("usage: mv old_file new_file\n");
}

int
main(int argc, char** argv) {
    if (argc < 3) {
        usage();
        exit(-1);
    }
    else {
        int destfd, srcfd;
        if ((srcfd = open(argv[1], O_RDONLY)) < 0) {
            return srcfd;
        }
        if ((destfd = open(argv[2], O_RDWR | O_CREAT)) < 0) {
            return destfd;
        }
        mv(srcfd, destfd, argv[1]);
    }
    return 0;
}


